package com.killers.cold.controller.api;

import com.killers.cold.model.Result;
import com.killers.cold.service.IFileDownloadService;
import com.killers.cold.service.IFileUploadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;

/**
 * 为用户提供的接口
 * @author 罗天豪
 * @date 2019/9/4
 */
@RestController
@RequestMapping("/api")
public class FileAPIController {

    @Autowired
    private IFileUploadService fileUploadService;

    @Autowired
    private IFileDownloadService fileDownloadService;


    /**
     * 1.上传单个文件
     * @param file 文件
     * @param userId 用户Id
     * @return 包装了ColdKillersFile的Result
     */
    @PostMapping("/single")
    public Result saveFile(@RequestParam("file")MultipartFile file, @PathVariable("userId")String userId) {
        return Result.genSuccessResult(fileUploadService.saveFile(file,userId));
    }


    /**
     * 上传多个文件
     * @param files 文件list
     * @param userId 用户Id
     * @return 包含文件信息的list
     */
    @PostMapping("/multiple")
    public Result saveFiles(@RequestParam("files") ArrayList<MultipartFile> files, @PathVariable("userId")String userId) {
        return Result.genSuccessResult(fileUploadService.saveFiles(files,userId));
    }


    /**
     * 用户下载文件
     * @param fileId 文件唯一标识
     * @param userId 用户唯一标识
     * @return 下载的文件信息
     */
    @GetMapping
    public ResponseEntity downloadFile(@RequestParam("fileId")String fileId,
                                       @PathVariable("userId")String userId,
                                       HttpServletResponse httpServletResponse) throws IOException {
        fileDownloadService.getFile(fileId, userId, httpServletResponse);
        return new ResponseEntity<>(HttpStatus.OK);
    }
}
